﻿#include "logger.h"

extern "C" __declspec(dllexport) ITLogger* GetInstance()
{
    return dynamic_cast<ITLogger*>(Logger::GetInstance());
}

Logger::Logger()
{
    m_IsOpenLog     = false;
}

Logger::~Logger()
{

}

TRESULT Logger::Init()
{
    connect(this, &Logger::sigPostTrdMsg, this, &Logger::slotGetTrdMsg);
    this->moveToThread(&m_thread);
    TRESULT ret = T_FALSE;
    //create log
    if(!QFile::exists("./Logger"))
    {
        QDir dir;
        dir.mkdir("./Logger");
    }
    QDateTime time = QDateTime::currentDateTime();
    QString strfile = QString("./Logger/%0.txt").arg(time.toString("yyyyMMdd_hhmm"));
    m_file.setFileName(strfile);
    if(m_file.open(QIODevice::WriteOnly | QIODevice::Append))
    {
        m_file.write("Logger::Init() \t\n");
        m_file.flush();
        m_IsOpenLog = true;
        //start thread
        m_thread.start();
        ret = T_OK;
    }
    return ret;
}

TRESULT Logger::UnInit(int nTime)
{
    qDebug() << "Logger::UnInit()";
    m_thread.quit();
    if(m_thread.wait(nTime))
    {
        m_thread.terminate();
        m_thread.wait(nTime);
    }
    if(m_IsOpenLog)
    {
        m_file.close();
        m_IsOpenLog = false;
    }
    return T_OK;
}

TRESULT Logger::SetFramework(ITFramework *pFrm)
{
    m_pFramework = pFrm;
    return T_OK;
}

TRESULT Logger::WriteLog(const char *szLog, int level)
{

    TmLogMsg *msg = new TmLogMsg;
    msg->msgtype = Logger_Log;
    msg->lParam = level;
    memcpy(msg->szParam2, szLog, sizeof(msg->szParam2));
    m_mutex.lock();
    m_listLog.push_back(msg);
    m_mutex.unlock();
    emit sigPostTrdMsg();
    return T_OK;
}

TRESULT Logger::WriteMemory(const char *userId, int M)
{
    return T_OK;
}

TRESULT Logger::WriteUserSign(const char *userId, bool bIsSign)
{
    return T_OK;
}

TRESULT Logger::ClearUserSign()
{
    return T_OK;
}

TRESULT Logger::GetMemory()
{
    return T_OK;
}

TRESULT Logger::CollectData(int nEventId, char *userId, char *username)
{
    return T_OK;
}

void Logger::writeLogger(const char *szLog, int level)
{
    if(m_IsOpenLog)
    {
        QDateTime time = QDateTime::currentDateTime();
        QString strTimer = time.toString("yyyy-MM-dd hh:mm:ss");
        m_szLog = QString("Tami[%0 Level(%1)]:%2 \t\n")
                .arg(strTimer)
                .arg(level)
                .arg(szLog);
        m_file.write(m_szLog.toUtf8().data());
        m_file.flush();
        qDebug() << m_szLog.toUtf8().data();
    }
}

void Logger::slotGetTrdMsg()
{
    if(!m_listLog.empty())
    {
        TmLogMsg* msg = NULL;
        m_mutex.lock();
        msg = m_listLog.front();
        m_listLog.pop_front();
        m_mutex.unlock();
        if(NULL == msg)
            return;
        switch(msg->msgtype)
        {
        case Logger_Log:
        {
            writeLogger(msg->szParam2, msg->lParam);
        }
            break;
        default: break;
        }

        ///////////////////
        SAFE_DELETE(msg);
    }
}
